<template>
  <div class="login">
      <div class="login-bg"></div>
      <div class="table">
          <div class="table-cell">
            <img src="../../assets/logo.png" class="logo">
            <mu-container>
                <mu-form ref="form" :model="validateForm" class="mu-demo-form">
                    <mu-form-item label="用户名" help-text="" prop="username" :rules="usernameRules">
                        <mu-text-field v-model="validateForm.username" prop="username" @keyup.enter.native="submit" ></mu-text-field>
                    </mu-form-item>
                    <mu-form-item label="密码" prop="password" :rules="passwordRules">
                        <mu-text-field type="password" v-model="validateForm.password" prop="password" :help-text="tips" @keyup.enter.native="submit" ></mu-text-field>
                    </mu-form-item>
                    <mu-checkbox v-model="isAutoLogin" label="记住我"></mu-checkbox>
                    <mu-form-item class="login-btn">
                        <mu-button color="primary" large @click="submit">登 陆</mu-button>
                    </mu-form-item>
                </mu-form>
            </mu-container>
          </div>
      </div>
  </div>
</template>

<script>
import api from "@/common/api"
export default {
  data () {
    return {
      usernameRules: [
        { validate: (val) => !!val, message: '必须填写用户名'},
        { validate: (val) => val.length >= 1, message: '用户名长度大于1'}
      ],
      passwordRules: [
        { validate: (val) => !!val, message: '必须填写密码'},
        { validate: (val) => val.length >= 1 && val.length <= 999, message: '密码长度大于1'}
      ],
      validateForm: {
        username: '',
        password: ''
      },
      tips: "",
      isAutoLogin: false,
      requestOnce: true // 重复提交FLAG
    }
  },
  methods: {
    submit () {
        // this.common.tts("登陆中")
        if(this.validateForm.username.toLocaleLowerCase() == 'z'){
            localStorage.clear();
            this.$router.push({name:'loading'});
        }else if(this.validateForm.username.toLocaleLowerCase() == 'b'){
            this.$router.push({name:'ble'});
        }else{
            this.loging();
        }
    },
    loging () {
        // this.common.tts('您有一个挑车出库任务.')
        let bs = window.plus ? plus.device.uuid : 'equipmentBS';
        this.$refs.form.validate().then((result) => {
            if(result){
                let data = {
                    "deviceId": bs, //设备唯一标识
                    "content": {
                        "deviceId": bs, //设备唯一标识
                        "username": this.validateForm.username, //登录用户名
                        "passwordHash": this.common.getPasswords(this.validateForm.password) //登录密码密文
                    }
                }
                // 每次登陆的时候记住用户名和密码
                if(this.isAutoLogin){
                    localStorage.setItem('username',this.validateForm.username)
                    localStorage.setItem('password',this.validateForm.password)
                }else{
                    localStorage.removeItem('username'),
                    localStorage.removeItem('password');
                }
                // 提示
                this.Toast.loading({message: '登陆中...'});
                
                if(this.requestOnce){
                    this.requestOnce = false;
                    /* 发送post请求 */
                    this.common.reqData(api.app('login'), data, res=>{
                        this.requestOnce = true;
                        if(res.data.status == 200){
                            this.Toast.clear();
                            // 提示
                            this.Toast({
                                duration: 1000,
                                message: res.data.msg
                            });
                        }else if(res.data.status == 100){
                            console.log(api.app('login'));
                            //this.common.tts('叮咚，登陆成功。');
                            // this.common.tts("请求超时，请骚后在世")
                            // 查询仓库和任务中心
                            this.getWarehouses(data);
                            this.$store.commit('setAutoLoginStatus')
                            this.$store.commit('logined', {
                                clientId: res.data.content.clientId,
                                deviceId: bs,
                                name: res.data.content.name,
                                status: res.data.content.status,
                                interval: res.data.content.interval,
                                mqtt: res.data.content.mqtt,
                                post: res.data.content.post,
                                warehouse: res.data.content.warehouse
                            })
                            console.log("BS",bs);
                            this.$store.commit('setReasons', res.data.content.refuseReasons);
                            this.validateForm = {
                                username: '',
                                password: ''
                            }
                            window.localStorage.setItem('beDriverBindCard', res.data.content.beDriverBindCard);
                            this.Toast.clear();
                            this.$router.push({ path: "/home" })
                        }
                        console.log("登陆返回数据：",res.data)
                    },err =>{
                        this.requestOnce = true;
                        // 提示
                        this.Toast({
                            mask: true,
                            message: '请求超时，检查你的网络或稍后再试'
                        });
                        console.log(err)
                    });
                }
            }
        });
    },
    getAbnormal () {
        let getDisance = this.common.getDisance;
        // 获取异常
        this.common.reqData(api.app('abnormalInfo'), {}, res=>{
            if(res.data.status == 100){
                this.$store.commit('getAbnormal', res.data.content.exceptionTypes)
            }
        },err =>{
            console.log(err)
        });
    },
    getWarehouses (opt) {
        let getDisance = this.common.getDisance;
        // 查询仓库和任务中心
        this.common.reqData(api.app('warehouseInfo'), opt, res=>{
            console.log("仓库和任务中心:", res.data)
            if(res.data.status == 100){
                this.$store.commit('setWarehouses', res.data.content.warehouses);
            }
        },err =>{
            console.log(err)
            this.Toast.clear();
        });
    },
    autoLogining () {
        // 记住登陆状态
        let autoLogin = localStorage.getItem('isAutoLogin');
        if(autoLogin){
            if(autoLogin == 'true'){
                this.isAutoLogin = true;
                this.isLocalUser();
            }else{
                this.isAutoLogin = false;
            }
        }else{
            // 没有存储时
            localStorage.setItem('isAutoLogin',this.isAutoLogin)
        }
    },
    isLocalUser () {
        let username = localStorage.getItem('username');
        let password = localStorage.getItem('password');
        this.localStorageUser(1, username);
        this.localStorageUser(2, password);
    },
    localStorageUser (id, opt) {
        if(opt){
            id == 1 ? this.validateForm.username = opt : this.validateForm.password = opt;
            // 自动登陆
            this.$store.state.autoLoginStatus ? this.submit() : false;
        } else {
            this.validateForm.username = '';
            this.validateForm.password = '';
        }
    }
  },
  watch: {
    isAutoLogin () {
        localStorage.setItem('isAutoLogin', this.isAutoLogin)
    }
  },
  mounted () {
    // 获取异常
    this.getAbnormal();
    // 是否记住自动登陆
    this.autoLogining();
    // 清空缓存菜单
    this.$store.commit('initMeun');
    // ------ //
    console.log("(╯°□°）╯︵ ┻━┻");
    // ------ //
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.login{
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
    overflow: hidden;
}
.login-bg{
    width:100%;
    height:100%;
    position: absolute;
    background-image: url(../../assets/login.png);
    background-size: cover;
    padding:1px;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    box-sizing:border-box;
}
.login-bg:after{
    content: "";
    width:100%;
    height:100%;
    position: absolute;
    left:0;
    top:0;
    background: inherit;
    -webkit-filter: blur(5px);
    filter: blur(5px);
}
.table{
    width: 100%;
    height: 100%;
    display: table;
    text-align: center;
}
.table-cell{
    display: table-cell;
    vertical-align: middle;
}
.login-input{
    margin: 0 0 15px;
}
.login-form{
    width: 80%;
    margin: 0 auto 15px;
}
.van-cell-group{
    background: none;
}
.van-cell{
    background: rgba(255,255,255,0.45);
}
.logo{
    z-index: 999;
    position: relative;
    margin: 0 0 20px;
}
/* login */
.mu-demo-form {
  width: 80%;
  max-width: 460px;
  margin: 0 auto ;
  text-align: left;
}
</style>
